/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.promo;

import com.toedter.calendar.JDateChooser;
import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SpinnerDateModel;
import main.ServicesList;
import model.promo.Promo;
import org.apache.log4j.Logger;
import utility.NameValueList;
import utility.StringUtils;
import utility.com.ComponentUtils;
import utility.com.InputValidation;
import utility.typeSafe.EnumUtils;
import utility.typeSafe.PromoJenis;
import view.DialogTemplate;

/**
 *
 * @author jay
 */
public class PromoFrm extends DialogTemplate {

    private Promo promo;
    private Object oldValue, newValue;
    private List<NameValueList> jenisList = EnumUtils.enumToNameValueList(PromoJenis.class);
    private static Logger log = Logger.getLogger(PromoFrm.class);

    public PromoFrm() {
        super(ServicesList.MAIN_FRAME, true);
        initComponents();
        initComponentsRules();
    }
   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtNama = new javax.swing.JTextField();
        cmbJenisPromo = new javax.swing.JComboBox();
        chkMember = new javax.swing.JCheckBox();
        chkNonMember = new javax.swing.JCheckBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtNotes = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        btnSave = new javax.swing.JButton();
        btnNew = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        spnJamMulai = new javax.swing.JSpinner();
        spnJamAkhir = new javax.swing.JSpinner();
        txtSetup = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        txtNama.setName("txtNama"); // NOI18N

        cmbJenisPromo.setName("cmbJenisPromo"); // NOI18N

        chkMember.setText("Member");
        chkMember.setName("chkMember"); // NOI18N

        chkNonMember.setText("Non Member");
        chkNonMember.setName("chkNonMember"); // NOI18N

        txtNotes.setColumns(20);
        txtNotes.setRows(5);
        txtNotes.setName("txtNotes"); // NOI18N
        jScrollPane1.setViewportView(txtNotes);

        jLabel1.setText("Nama :");

        jLabel4.setText("Mulai Dari :");

        jLabel5.setText("Sampai Dengan :");

        jLabel6.setText("Jenis Promo :");

        jLabel7.setText("Berlaku Untuk :");

        jLabel8.setText("Keteranga :");

        btnSave.setText("Simpan");
        btnSave.setName("btnSave"); // NOI18N
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnNew.setText("Tambah");
        btnNew.setName("btnNew"); // NOI18N
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });

        btnClose.setText("Keluar");
        btnClose.setName("btnClose"); // NOI18N
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        spnJamMulai.setName("spnJamMulai"); // NOI18N

        spnJamAkhir.setName("spnJamAkhir"); // NOI18N

        txtSetup.setText("Setup Barang");
        txtSetup.setName("btnNew"); // NOI18N
        txtSetup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSetupActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNama)
                            .addComponent(jScrollPane1)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(chkMember)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(chkNonMember))
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(spnJamAkhir, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 79, Short.MAX_VALUE)
                                        .addComponent(spnJamMulai, javax.swing.GroupLayout.Alignment.LEADING))
                                    .addComponent(cmbJenisPromo, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 132, Short.MAX_VALUE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(txtSetup)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnNew)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSave)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnClose)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(spnJamMulai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(spnJamAkhir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbJenisPromo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(chkMember)
                    .addComponent(chkNonMember)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnNew)
                    .addComponent(btnClose)
                    .addComponent(txtSetup))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        validasi();
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        initForm();
        txtNama.requestFocus();
    }//GEN-LAST:event_btnNewActionPerformed

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
         dispose();
    }//GEN-LAST:event_btnCloseActionPerformed

    private void txtSetupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSetupActionPerformed
        setupItemPromo();
    }//GEN-LAST:event_txtSetupActionPerformed

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnSave;
    private javax.swing.JCheckBox chkMember;
    private javax.swing.JCheckBox chkNonMember;
    private javax.swing.JComboBox cmbJenisPromo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSpinner spnJamAkhir;
    private javax.swing.JSpinner spnJamMulai;
    private javax.swing.JTextField txtNama;
    private javax.swing.JTextArea txtNotes;
    private javax.swing.JButton txtSetup;
    // End of variables declaration//GEN-END:variables

    @Override
    public int execute(int id) {
        setLocationRelativeTo(null);
        initForm();
        if (id!=0) { loadData(id); }

        setVisible(true);
        if (promo!=null) {
        return promo.getId();}
        else { return 0; }
    }

    @Override
    protected void initForm() {
        promo = new Promo();
        
        txtNama.setText("");
        chkMember.setSelected(false);
        chkNonMember.setSelected(true);
        txtNotes.setText("");
        cmbJenisPromo.setSelectedIndex(0);
        
        String time = StringUtils.formatDate(StringUtils.truncDate(new Date()))+ " 00:00";
        DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        try {
            Date date = sdf.parse(time);            
            spnJamAkhir.setValue(date);
            spnJamMulai.setValue(date);
        } catch (Exception e) {}
        
    }

    @Override
    protected void loadData(int id) {
        promo = ServicesList.getPromoService().getPromo(id);
        if (promo != null) {
            txtNama.setText(promo.getPromoName());
            txtNotes.setText(promo.getNotes());
            spnJamAkhir.setValue(promo.getEndDate());
            spnJamMulai.setValue(promo.getStartDate());
            cmbJenisPromo.setSelectedIndex(NameValueList.indexOf(jenisList, promo.getJenis()));
            getWhois();
        }
    }

    @Override
    protected void saveData() {
        promo.setPromoName(txtNama.getText());
        promo.setNotes(txtNotes.getText());
        promo.setStartDate((Date)spnJamMulai.getValue());
        promo.setEndDate((Date)spnJamAkhir.getValue());
        promo.setJenis(((NameValueList) cmbJenisPromo.getSelectedItem()).getKey());
        setWhois();
                 
        boolean saved = false;
        try{
            saved = ServicesList.getPromoService().save(promo);
            
        } catch(Exception ex){
            log.error(ex);
            JOptionPane.showMessageDialog(this, "Data gagal disimpan."
            ,"Error",JOptionPane.ERROR_MESSAGE);
        }
        
        initButtonState(!saved);
    }

    @Override
    protected void validasi() {
        if (txtNama.getText()==null) {txtNama.setText("");}
        if (InputValidation.isValid(txtNama, !"".equals(txtNama.getText()), "Nama belum diisi.")) {
        if (InputValidation.isValid(cmbJenisPromo, cmbJenisPromo.getSelectedItem() != null, "Jenis promo belum diisi.")) {
            saveData();
        }}
    }

    @Override
    protected void moveNext() {
        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        manager.focusNextComponent();
    }

    @Override
    protected void initButtonState(boolean status) {
        btnSave.setEnabled(status);
    }
    
    @Override
    public void setVisible(boolean value) {
        super.setVisible(value);
        txtNama.requestFocusInWindow();
    }
    
    private void setWhois() {
        String whois = "";
        if(chkMember.isSelected()) { whois = whois.concat("1"); }
        else { whois = whois.concat("0"); }
        
        if(chkNonMember.isSelected()) { whois = whois.concat("1"); }
        else { whois = whois.concat("0"); }
        
        promo.setWhois(whois);
    }
    
    private void getWhois() {
        if (promo.getWhois()!=null) {
            String whois = promo.getWhois();
            if (whois == null || whois.isEmpty()) {
                whois = "00";
            }

            String j01 = whois.substring(0, 1);
            String j02 = whois.substring(1, 2);
            chkMember.setSelected("1".equals(j01) ? true:false);
            chkNonMember.setSelected("1".equals(j02) ? true:false);
        }
    }
    
    private void setupItemPromo() {
        if (promo.getId() > 0) {
            
            if (PromoJenis.PROMO_PRICE.toString().equals(promo.getJenis())) {
                new PromoPriceFrm().execute(promo.getId());
            }else if (PromoJenis.PROMO_DISKON_ITEM.toString().equals(promo.getJenis())) {
                new PromoDisitemFrm().execute(promo.getId());
            }else if (PromoJenis.PROMO_DISKON_STRUK.toString().equals(promo.getJenis())) {
                new PromoDistrukFrm().execute(promo.getId());
            }
        }
    }
    
    class ActionKeyListener implements KeyListener {
        @Override public void keyTyped(KeyEvent e) {} 
        @Override public void keyReleased(KeyEvent e) {}
        @Override public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) { 
                case KeyEvent.VK_ENTER: moveNext(); break;
            }
        }
    }
    
    class ActionFocusGained implements FocusListener {
        @Override public void focusGained(FocusEvent e) { 
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { oldValue = ((JTextField) componen).getText();
            }else if (componen instanceof JSpinner) { oldValue = ((JSpinner) componen).getValue();
            }else if (componen instanceof JComboBox) { oldValue = ((JComboBox) componen).getSelectedIndex();
            }else if (componen instanceof JCheckBox) { oldValue = ((JCheckBox) componen).isSelected();
            }else if (componen instanceof JTextArea) { oldValue = ((JTextArea) componen).getText(); 
            }else if (componen instanceof JDateChooser) { oldValue = ((JDateChooser) componen).getDate(); }
        }
        
        @Override public void focusLost(FocusEvent e) {
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { newValue = ((JTextField) componen).getText();
            }else if (componen instanceof JSpinner) { newValue = ((JSpinner) componen).getValue();
            }else if (componen instanceof JComboBox) { newValue = ((JComboBox) componen).getSelectedIndex();
            }else if (componen instanceof JCheckBox) { newValue = ((JCheckBox) componen).isSelected();
            }else if (componen instanceof JTextArea) { oldValue = ((JTextArea) componen).getText(); 
            }else if (componen instanceof JDateChooser) { newValue = ((JDateChooser) componen).getDate(); }
            
            if (!newValue.equals(oldValue)) { initButtonState(true); }
        }
    }
    
    private void initComponentsRules() {
        btnClose.registerKeyboardAction(btnClose.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);
 
        btnClose.registerKeyboardAction(btnClose.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);
        
        btnNew.registerKeyboardAction(btnNew.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);

        btnNew.registerKeyboardAction(btnNew.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);

        btnSave.registerKeyboardAction(btnSave.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);
 
        btnSave.registerKeyboardAction(btnSave.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);
        
        spnJamMulai.setModel(new SpinnerDateModel());
        JSpinner.DateEditor deAwal = new JSpinner.DateEditor(spnJamMulai, "dd/MM/yyyy HH:mm");
        spnJamMulai.setEditor(deAwal);
        
        spnJamAkhir.setModel(new SpinnerDateModel());
        JSpinner.DateEditor deAkhir = new JSpinner.DateEditor(spnJamAkhir, "dd/MM/yyyy HH:mm");
        spnJamAkhir.setEditor(deAkhir);
  
        cmbJenisPromo.setModel(ComponentUtils.getDefaultComboBoxModel(jenisList));

        txtNama.addKeyListener(new ActionKeyListener());
        txtNama.addFocusListener(new ActionFocusGained());
        txtNotes.addKeyListener(new ActionKeyListener());
        txtNotes.addFocusListener(new ActionFocusGained());
        spnJamAkhir.addKeyListener(new ActionKeyListener());
        spnJamAkhir.addFocusListener(new ActionFocusGained());
        spnJamMulai.addKeyListener(new ActionKeyListener());
        spnJamMulai.addFocusListener(new ActionFocusGained());
        
        cmbJenisPromo.addKeyListener(new ActionKeyListener());
        chkMember.addKeyListener(new ActionKeyListener());
        chkNonMember.addKeyListener(new ActionKeyListener());
        cmbJenisPromo.addFocusListener(new ActionFocusGained());
        chkMember.addFocusListener(new ActionFocusGained());
        chkNonMember.addFocusListener(new ActionFocusGained());
    }      
}
